Page({
  data: {
    playlist: [],
    playlistInfo: {}
  },
  onLoad(options) {
    const playlistId = parseInt(options.id)
    const config = require('../../utils/config')
    
    // 获取歌单信息和歌曲列表
    const playlistInfo = config.getPlaylistInfo(playlistId)
    const songs = config.getPlaylistSongs(playlistId)
    
    // 添加收藏状态
    const app = getApp()
    const songsWithFavoriteStatus = songs.map(song => ({
      ...song,
      isFavorite: app.isFavorite(song.id)
    }))
    
    this.setData({
      playlist: songsWithFavoriteStatus,
      playlistInfo: playlistInfo
    })
  },

  onShow() {
    // 更新收藏状态
    this.updateFavoriteStatus()
  },
  playSong(e) {
    const song = e.currentTarget.dataset.song
    const songIndex = this.data.playlist.findIndex(item => item.id === song.id)
    const app = getApp()
    
    // 设置当前播放的歌曲和播放列表
    app.globalData.currentSong = song
    app.globalData.currentPlaylist = this.data.playlist
    app.globalData.currentSongIndex = songIndex
    app.globalData.isPlaying = true
    
    // 调用播放函数
    app.playSong(song)
    
    // 跳转到播放页面
    wx.navigateTo({
      url: `/pages/player/player?musicId=${song.id}&name=${encodeURIComponent(song.name)}&artist=${encodeURIComponent(song.artist)}&cover=${encodeURIComponent(song.picUrl || '/assets/default-cover.svg')}&duration=${encodeURIComponent(song.duration || '00:00')}`
    })
  },

  // 切换收藏状态
  toggleFavorite(e) {
    e.stopPropagation()
    const song = e.currentTarget.dataset.song
    const app = getApp()
    
    // 使用app中的统一收藏方法
    const result = app.toggleFavorite(song)
    
    // 更新收藏状态
    this.updateFavoriteStatus()
  },

  // 更新收藏状态
  updateFavoriteStatus() {
    const app = getApp()
    const playlist = this.data.playlist.map(song => ({
      ...song,
      isFavorite: app.isFavorite(song.id)
    }))
    
    this.setData({
      playlist: playlist
    })
  },
  deleteSong(e) {
    const songId = e.currentTarget.dataset.id
    const app = getApp()
    
    app.globalData.playlist = app.globalData.playlist.filter(item => item.id !== songId)
    this.setData({
      playlist: app.globalData.playlist
    })
  }
})